package roleimpl

import (
	"github.com/casbin/casbin/v2"
	"github.com/casbin/casbin/v2/log"
	"github.com/casbin/casbin/v2/model"
	gormadapter "github.com/casbin/gorm-adapter/v3"
	"gorm.io/gorm"
)

// Initialize the model from a string.
var text = `
[request_definition]
r = sub, obj, act

[policy_definition]
p = sub, obj, act

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = r.sub == p.sub && (keyMatch2(r.obj, p.obj) || keyMatch(r.obj, p.obj)) && (r.act == p.act || p.act == "*")
`

func newCasbinEnforcer(db *gorm.DB) *casbin.SyncedEnforcer {
	adapter, err := gormadapter.NewAdapterByDB(db)
	if err != nil {
		panic(err)
	}
	m, err := model.NewModelFromString(text)
	if err != nil {
		panic(err)
	}
	en, err2 := casbin.NewSyncedEnforcer(m, adapter)
	en.SetLogger(&log.DefaultLogger{})
	en.EnableLog(true)
	if err2 != nil {
		panic(err)
	}
	en.LoadPolicy() //加载规则
	return en
}
func (s sqlStore) CheckEnforce(roleKey, method, path string) (bool, error) {
	s.enforcer.LoadPolicy() //fix:解决后台赋权限之后刷新权限无效问题
	return s.enforcer.Enforce(roleKey, method, path)
}
func (s sqlStore) BatchCheckEnforce(request [][]interface{}) ([]bool, error) {
	return s.enforcer.BatchEnforce(request)
}
func (s sqlStore) AddPolicy(polices [][]string) error {
	if len(polices) == 0 {
		return nil
	}
	_, err := s.enforcer.AddNamedPolicies("p", polices)
	if err != nil {
		return err
	}
	err = s.enforcer.SavePolicy()
	return err
}
func (s sqlStore) UpdatePolicy(roleKey string, polices [][]string) error {
	_, err := s.enforcer.RemoveFilteredPolicy(0, roleKey)
	if err != nil {
		return err
	}
	return s.AddPolicy(polices)
}
func (en sqlStore) DeletePolicy(roleKey string) error {
	_, err := en.enforcer.RemoveFilteredPolicy(0, roleKey)

	return err
}
